﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;

public partial class Manager_OrderDetail_SignOrderFilm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(Manager_OrderDetail_SignOrderFilm));
        if (!IsPostBack)
        {
            if (Session["AdminUserID"] == null)
            {
                Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
                return;
            }

            if (Session["IsAdmin"] != "S")
            {
                clsGetMenuAuth clsAuth = new clsGetMenuAuth(Session["AdminUserID"].ToString(), Session["AutID"].ToString(), Session["IsAdmin"].ToString(), Request.QueryString["CodeID"]);
                if (clsAuth.IsSignAuth() == false)
                    pnlControl.Visible = false;
            }
            BindData();
            VisibleButton();

        }
    }


    protected DataSet GetStoreList()
    {
        clsWebShop cls = new clsWebShop();
        DataSet ds = cls.Get_StoreByKindNoNoneProc();
        return ds;

    }

    private DropDownList BindStoreList(DropDownList ddlStore)
    {
        clsWebShop cls = new clsWebShop();
        ListItem item = new ListItem();
        ddlStore.DataSource = cls.Get_StoreByKindNoNoneProc().Tables[0];
        ddlStore.DataTextField = "StName";
        ddlStore.DataValueField = "StID";
        ddlStore.DataBind();
        item.Text = "Tất cả";
        item.Value = "0";
        ddlStore.Items.Insert(0, item);
        ddlStore.SelectedItem.Selected = false;
        return ddlStore;

    }
    private void VisibleButton()
    {
        string State = Request.QueryString["State"];
        if (State == "Y")
        {
            lblTitle.Text = "ĐƠN ĐÃ XÁC NHẬN";
            btnOk.Visible = false;
            btnCancel.Visible = true;
            btnSending.Visible = true;
            btnSend.Visible = false;

            tdNote.Visible = true;


        }
        else if (State == "S")
        {
            lblTitle.Text = "ĐƠN ĐANG THỰC HIỆN";
            btnOk.Visible = false;
            btnCancel.Visible = true;
            btnSending.Visible = false;
            btnSend.Visible = true;

            tdNote.Visible = true;
            txtNote.ReadOnly = true;


        }
        else if (State == "C")
        {
            lblTitle.Text = "ĐƠN ĐÃ HỦY";
            btnOk.Visible = true;
            btnCancel.Visible = false;
            btnSend.Visible = false;
            btnSending.Visible = false;

            tdNote.Visible = true;



        }
        else if (State == "E")
        {
            lblTitle.Text = "ĐƠN ĐÃ THỰC HIỆN";
            btnOk.Visible = false;
            btnCancel.Visible = false;
            btnSend.Visible = false;

            btnSending.Visible = false;
            tdNote.Visible = true;
            txtNote.ReadOnly = true;
            txtNote.BackColor = System.Drawing.Color.FromName("AliceBlue");


            /*for (int i = 0; i < grvMaster.Rows.Count; i++)
            {
                CheckBox chkApprove = (CheckBox)grvMaster.Rows[i].FindControl("chkApprove");
               // chkApprove.Visible = false;
            }*/
        }
        else
        {
            lblTitle.Text = "ĐƠN CHỜ XÁC NHẬN";
            btnOk.Visible = true;
            btnCancel.Visible = true;
            btnSending.Visible = false;
            btnSend.Visible = false;

            tdNote.Visible = true;
            txtNote.ReadOnly = true;


        }



    }
    private void BindData()
    {
        clsWebShop cls = new clsWebShop();
        clsCommon clsCom = new clsCommon();
        //Lay so luong trong kho
        //Session["dtCountStore"] = cls.Get_QuantityStoreGroup("", "0").Tables[0];
        DataTable dt;
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("StartDate", "");
        msg.CreateFirstNode("EndDate", "");
        msg.CreateFirstNode("Status", Request.QueryString["State"]);
        msg.CreateFirstNode("End_MK", "");
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        dt = cls.Get_OrderFilmByCondition(msg.GetXmlStr.ToString()).Tables[0];


        if (dt.Rows.Count > 0)
        {
            lblMaDH.Text = dt.Rows[0]["OrderID"].ToString();
            lblTenKH.Text = dt.Rows[0]["CusNm"].ToString();
            // lblTaxNo.Text = clsCom.FormatDate(dt.Rows[0]["BirthDay"].ToString());
            lblDiaChi.Text = dt.Rows[0]["Address"].ToString();
            lblNoichon.Text = dt.Rows[0]["PlaceNm"].ToString();
            lblSDT.Text = dt.Rows[0]["Phone"].ToString();
            lblEmail.Text = dt.Rows[0]["Email"].ToString();
            lblTaxNo.Text = dt.Rows[0]["TaxNo"].ToString();
            if (lblTaxNo.Text.Trim() == "")
            {
                trTaxNo.Visible = false;
            }



            txtNote.Text = dt.Rows[0]["Note"].ToString();
            if (txtNote.Text == "")
                Label2.Visible = false;

            if (dt.Rows[0]["Note_Cus"].ToString().Trim() != "")
            {
                lblNoteCus.Text = dt.Rows[0]["Note_Cus"].ToString();
            }
            lblContent.Text = "<a href='" + ResolveUrl("~/") + "Database/ListFilm/" + dt.Rows[0]["OrderID"].ToString() + ".csv'>" + dt.Rows[0]["OrderID"].ToString() + ".csv</a>";
            
        }
    }
    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public string GetQuantityStore(string PDID, string StID)
    {
        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("PdID", PDID);
        msg.CreateFirstNode("StID", StID);
        DataTable dt = cls.Get_QuantityStoreByCondition(msg.GetXmlStr).Tables[0];
        if (dt.Rows.Count > 0)
            return dt.Rows[0][0].ToString();
        return "0";

    }

    protected void grvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string End_MK = DataBinder.Eval(e.Row.DataItem, "End_MK").ToString();
            string U_Status = DataBinder.Eval(e.Row.DataItem, "U_Status").ToString();
            if (End_MK == "D") //Don & KH dang o trang thai xoa
            {
                e.Row.Cells[1].BackColor = System.Drawing.Color.Red;
            }
            if (U_Status == "D")
            {
                AutoNumber1.BgColor = "red";
            }
            Label lblQuantityStore = (Label)e.Row.FindControl("lblQuantityStore");
            DropDownList ddlStore = (DropDownList)e.Row.FindControl("ddlStore");
            Label lblDonGia = (Label)e.Row.FindControl("lblDonGia");
            TextBox lblTotal = (TextBox)e.Row.FindControl("lblTotal");
            if (DataBinder.Eval(e.Row.DataItem, "KindNo").ToString() == "P")
            {
                string sQ_Store = "0";
                clsWebShop cls = new clsWebShop();
                if (Request.QueryString["State"] == "S")
                {
                    string StID = DataBinder.Eval(e.Row.DataItem, "StID").ToString();
                    if (StID != "" && StID != "0")
                        ddlStore.Items.FindByValue(StID).Selected = true;
                    /*if (DataBinder.Eval(e.Row.DataItem, "RemainPrice").ToString() == "0" || DataBinder.Eval(e.Row.DataItem, "RemainPrice").ToString() == "")
                    {
                        e.Row.Cells[8].Text = "Trả đủ tiền";
                    }*/
                }

                if (Request.QueryString["State"] != "N" && Request.QueryString["State"] != "E")
                {
                    DataTable dt = cls.Get_QuantityStoreGroup(DataBinder.Eval(e.Row.DataItem, "PDID").ToString(), ddlStore.SelectedValue).Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        sQ_Store = dt.Rows[0]["Quantity_Store"].ToString();
                    }
                    lblQuantityStore.Text = sQ_Store;
                    if (Request.QueryString["State"] == "Y" || Request.QueryString["State"] == "S")
                    {
                        ddlStore.Visible = true;
                        if (int.Parse(lblQuantityStore.Text) < int.Parse(e.Row.Cells[3].Text))
                            e.Row.Cells[5].BackColor = System.Drawing.Color.Orange;

                    }
                    else
                    {
                        if (int.Parse(lblQuantityStore.Text) < int.Parse(e.Row.Cells[3].Text))
                            e.Row.Cells[5].BackColor = System.Drawing.Color.Orange;
                    }
                }

                lblDonGia.Text = FormatMoney(lblDonGia.Text);
                lblTotal.Text = FormatMoney(lblTotal.Text);

            }
            else
            {
                ddlStore.Visible = false;
                e.Row.Cells[5].BackColor = System.Drawing.Color.LightYellow;
                e.Row.Cells[7].Text = "";
                e.Row.Cells[8].Text = "";
                lblQuantityStore.Text = "Free";
            }
            if (Request.QueryString["State"] == "S" || Request.QueryString["State"] == "E")
            {
                TextBox txtNoteDetail = (TextBox)e.Row.FindControl("txtNoteDetail");
                txtNoteDetail.ReadOnly = true;
                txtNoteDetail.BorderStyle = BorderStyle.None;
            }



        }
    }
    protected void ddlStore_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindData();
    }

    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public string AjaxUpdateOrderState(string State, string sOrder)
    {
        clsWebShop cls = new clsWebShop();
        string myMsg = "";
        switch (State.ToLower())
        {
            case "save":
                cls.UpdateData("update OrderPD set Status='Y' where  OrderID='" + sOrder + "'");
                myMsg = "Y";
                break;
            case "cancel":
                cls.UpdateData("update OrderPD set Status='N' where  OrderID='" + sOrder + "'");
                myMsg = "N";
                break;
        }
        return myMsg;
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        Response.Redirect("OrderDetail.aspx?CodeID=" + Request.QueryString["CodeID"] + "&sDate=" + Request["sDate"].ToString() + "&eDate=" + Request["eDate"].ToString() + "&sDrop=" + Request["sDrop"].ToString() + "");

    }
    private string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }

    private string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }
    //Dang cho duyet
    protected void btnOk_Click(object sender, EventArgs e)
    {
        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        string xml = cls.Upd_WaitingSignOrderPD(msg.GetXmlStr);
        msg = new PccMsg(xml);
        string strOutput = msg.Query("strOutput");
        if (strOutput == "-2")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Trong đơn đặt hàng " + Request.QueryString["OrderID"] + ". Sản phẩm trong kho không đủ số lượng')</script>");
            BindData();
            return;
        }
        else
        {
            //INSERT FLOWORDERHIST
            clsFunAp clsFun = new clsFunAp();

            string Note = clsFun.NoteTo_Y("0", "0", " VNĐ");
            if (Request.QueryString["State"] == "C")
                Note = clsFun.NoteTo_Recover();

            msg = new PccMsg();
            msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
            msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
            msg.CreateFirstNode("Status", "Y");
            msg.CreateFirstNode("Note", Note);
            cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);

            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Xác nhận thành công');  window.location.href='" + strReturnPage() + "';</script>");

        }
    }

    //KET THUC DON
    protected void btnSend_Click(object sender, EventArgs e)
    {
        clsCommon clsCom = new clsCommon();
        //Update Trang Thai OrderPD= E
        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("Repaid", "0");
        msg.CreateFirstNode("RemainPrice", "0");
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        string xml = cls.Upd_EndOrderPD(msg.GetXmlStr);
        msg = new PccMsg(xml);
        string strOutput = msg.Query("strOutput");
        if (strOutput == "0")
        {
            //INSERT FLOWORDERHIST
            clsFunAp clsFun = new clsFunAp();

            msg = new PccMsg();
            msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
            msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
            msg.CreateFirstNode("Status", "E");
            msg.CreateFirstNode("Note", clsFun.NoteTo_E("0", "  VNĐ"));
            cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);

            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Xác nhận thành công');  window.location.href='" + strReturnPage() + "';</script>");



            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Giao hàng thành công');  window.location.href='" + strReturnPage() + "';</script>");

        }
        else//Undo
        {
            cls.UpdateData("Update OrderPD set Status='Y' where  OrderID='" + Request.QueryString["OrderID"] + "'");
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Có lỗi xác nhận đơn. Xin liên hệ với nhà quản trị')</script>");

        }
    }

    private void SendMailBasket(string OrderID)
    {

    }

    //Dang giao hang
    protected void btnSending_Click(object sender, EventArgs e)
    {

        //Update Trang Thai OrderPD= S
        clsWebShop cls = new clsWebShop();
        clsCommon clsCom = new clsCommon();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("Repaid", "0");
        msg.CreateFirstNode("RemainPrice", "0");
        msg.CreateFirstNode("Note", txtNote.Text);
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        string xml = cls.Upd_SendOrderPD(msg.GetXmlStr);

        msg = new PccMsg(xml);
        string strOutput = msg.Query("strOutput");
        if (strOutput == "0")
        {

            //INSERT FLOWORDERHIST
            clsFunAp clsFun = new clsFunAp();
            msg = new PccMsg();
            msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
            msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
            msg.CreateFirstNode("Status", "S");
            msg.CreateFirstNode("Note", clsFun.NoteTo_S("0", "0", " VNĐ"));

            cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);

            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Xác nhận đơn giao hàng thành công');  window.location.href='" + strReturnPage() + "';</script>");

        }
        else//Undo
        {
            UndoSendingOrder();
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Có lỗi xác nhận đơn. Xin liên hệ với nhà quản trị')</script>");

        }

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        clsWebShop cls = new clsWebShop();
        string sOrderID = Request.QueryString["OrderID"];
        /*if (Request.QueryString["State"] == "S")
        {
            cls.UpdateData("Update OrderPD set Status='C',Note='"+txtNote.Text+"',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "'  where  OrderID='" + Request.QueryString["OrderID"] + "'      update OrderDetail 	SET  Total=OldTotal,price= case 	when oldprice = 0 then   price 		else oldprice 	  end  where  OrderID='" + Request.QueryString["OrderID"] + "'");
        }
        else
        {
            cls.UpdateData("update OrderPD set Status='C',Note='" + txtNote.Text + "',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "' where  OrderID='" + sOrderID + "'");
        }*/

        cls.UpdateData("update OrderPD set Repaid='0',  RemainPrice='0',OldRemainPrice='0' , Status='C',Note='" + txtNote.Text + "',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "' where  OrderID='" + sOrderID + "'");

        //INSERT FLOWORDERHIST
        clsFunAp clsFun = new clsFunAp();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
        msg.CreateFirstNode("Status", "C");
        msg.CreateFirstNode("Note", clsFun.NoteTo_C());

        cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);

        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Hủy bỏ thành công');  window.location.href='" + strReturnPage() + "';</script>");
        //ReturnPage();
    }

    private string strReturnPage()
    {
        return "OrderDetail.aspx?CodeID=" + Request.QueryString["CodeID"] + "&sDate=" + Request.QueryString["sDate"] + "&eDate=" + Request.QueryString["eDate"] + "&sState=" + Request.QueryString["sState"] + "&sOrderID=" + Request.QueryString["sOrderID"] + "&PageIndex=" + Request.QueryString["PageIndex"];
    }

    private void ReturnPage()
    {
        Response.Redirect("OrderDetail.aspx?CodeID=" + Request.QueryString["CodeID"] + "&sDate=" + Request.QueryString["sDate"] + "&eDate=" + Request.QueryString["eDate"] + "&sState=" + Request.QueryString["sState"] + "&sOrderID=" + Request.QueryString["sOrderID"] + "&PageIndex=" + Request.QueryString["PageIndex"]);

    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        ReturnPage();
    }


    private void UndoEndOrder()
    {
        clsWebShop cls = new clsWebShop();
        // cls.UpdateData("Update OrderPD set Status='S' where  OrderID='" + Request.QueryString["OrderID"] + "'      update OrderDetail 	SET Repaid=0,RemainPrice=OldTotal,Total=OldTotal,price= case 	when oldprice = 0 then   price 		else oldprice 	  end  where  OrderID='" + Request.QueryString["OrderID"] + "'");
        cls.UpdateData("Update OrderPD set Status='S' where  OrderID='" + Request.QueryString["OrderID"] + "'  Delete Store_Product   Where OrderID='" + Request.QueryString["OrderID"] + "'");

    }

    private void UndoSendingOrder()
    {
        clsWebShop cls = new clsWebShop();
        cls.UpdateData("Update OrderPD set Status='Y' where  OrderID='" + Request.QueryString["OrderID"] + "' ");

    }
}